package com.gcloud.mesh.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtil {
	
	private static final String TYPE_FILE = "file";
	private static final String TYPE_DIR = "dir";
	
	public static List<String> listFilesAndDirs(String path) {
	    
		return list(path, null);
	}
	
	public static List<String> listFiles(String path) {
		
		return list(path, TYPE_FILE);
	}
	
	public static List<String> listDirs(String path) {
		
		return list(path, TYPE_DIR);
	}
	
	public static List<String> list(String path, String type) {
		List<String> files = new ArrayList<String>();
	    File file = new File(path);
	    File[] tempFiles = file.listFiles();
	    for(File f: tempFiles) {
	    	if(type == null) {
		    	if(f.isFile() || f.isDirectory()) {
		    		files.add(f.toString());
		    	}
		    	continue;
	    	}
	    	if(type.equals(TYPE_FILE)) {
	    		if(f.isFile()) {
		    		files.add(f.toString());
		    	}
		    	continue;
	    	}
	    	if(type.equals(TYPE_DIR)) {
	    		if(f.isDirectory()) {
		    		files.add(f.toString());
		    	}
		    	continue;
	    	}

	    }
	    return files;
	}
	
	public static boolean mkdir(String dir) {
		File path = new File(dir);
		if(path.exists()) {
			log.info("{} 目录已存在", path.getAbsolutePath());
			return true;
		}else {
			return path.mkdirs();
		}
	}
	
   public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
	    InputStream is = null;
	    BufferedReader reader = null;
        is = new FileInputStream(filePath);
        String line; 
        reader = new BufferedReader(new InputStreamReader(is));
        try {
            line = reader.readLine(); 
            while (line != null) { 
                buffer.append(line); 
                buffer.append("\n"); 
                line = reader.readLine(); 
            }
        }catch(Exception e) {
        	throw e;
        }finally {
        	reader.close();
            is.close();
        } 
    }
   
   public static String readFile(String filePath) throws IOException {
       StringBuffer sb = new StringBuffer();
       readToBuffer(sb, filePath);
       return sb.toString();
   }
   
}
